import storage from 'store'
import { welcome, removeToken } from '@/utils/util'
import { getUserInfo, getUser2 } from '@/api/user'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUser2({}).then((response) => {
          const result = response.data
          commit('SET_INFO', result)
          commit('SET_AVATAR', result.avatar)
          result.type = result.type.replace('5', '4')
          commit('SET_ROLES', result.type)
          commit('SET_NAME', { name: result.username, welcome: welcome() })
          resolve(response)
        }).catch((error) => {
          removeToken('pssid');
          reject(error)
        })
      })
    },
    GetInfo2({ commit }) {
      return new Promise((resolve, reject) => {
        getUser2({}).then(res => {
          if(res.data.avatar){
            commit('SET_AVATAR', res.data.avatar)
          }
          commit('SET_INFO', res.data)
          commit('SET_NAME', { name: res.data.nick_name ? res.data.nick_name : res.data.phone, welcome: welcome() })
          resolve(res)
        }).catch(err => {
          reject(err)
          console.log('error', err)
        })
      })
    }
  }
}

export default user
